﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WeChatGZHTextExtractor.DB
{
    public class SystemDataService : BaseService<SystemDataModel>
    {
        public T Get<T>(string key)
        {
            var model = Query(context => context.FirstOrDefault(n => n.Key == GetFormatKey(typeof(T), key)));
            if (model == null)
                return default(T);

            return model.Get<T>();
        }

        public void Set<T>(string key, T data)
        {
            Change(context =>
            {
                var model = context.FirstOrDefault(n => n.Key == GetFormatKey(typeof(T), key));
                if (model != null)
                {
                    model.Set(data);
                }
                else
                {
                    model = new SystemDataModel
                    {
                        Key = GetFormatKey(typeof(T), key),
                    };
                    model.Set(data);
                    context.Add(model);
                }
            });
        }

        public string GetFormatKey(Type type, string key)
        {
            return $"{type.FullName}::{key}";
        }
    }
}
